﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using University.Workshop.Model;
using System.IO;
using University.Workshop.Business;

namespace University.Workshop.WebApp
{
    public partial class MakeAOffer : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Product product=new Product();
            if (!User.Identity.IsAuthenticated)
                FormsAuthentication.RedirectToLoginPage();
            if(Session["prod"]!=null)
                product = Session["prod"] as Product;
            ProductName.Text = product.Name;
            ProductPrice.Text = product.Price.ToString();
            Currency.Text = product.Currency.ToString();
            Label4.Text = "Best Offer: (" + product.Currency.ToString() + ")";
            if (Directory.Exists(Server.MapPath("~/Thumbnails/") + product.ProductId + "/"))
            {
                DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Thumbnails/") + product.ProductId + "/");
                FileInfo[] currentImages = dir.GetFiles();
                string thumbUrl = "~/Thumbnails/" + product.ProductId + "/";
                foreach (FileInfo fi in currentImages)
                {
                    if (String.IsNullOrEmpty(ProductImage.ImageUrl))
                    {
                        ProductImage.ImageUrl = thumbUrl + fi.Name;
                    }
                }
            }
            else
            {
                ProductImage.ImageUrl = "~/Thumbnails/NoImage/noimage.jpg";
            }
        }

        protected void ReviewOffer_Click(object sender, EventArgs e)
        {
            try
            {
                Product prod = new Product();
                User user = new User();
                user = DataAccess.UserDataAccess.GetUserByEmail(User.Identity.Name);
                if (Session["prod"] != null)
                    prod = Session["prod"] as Product;
                Offer offer = new Offer();
                offer.OfferPrice = Convert.ToInt64(NewOffer.Text);
                offer.RelatedProduct = prod;
                offer.OfferDate = DateTime.Now;
                offer.BuyerId = user.Id;
                offer.Message = Message.Text;
                offer=OfferManager.MakeAOffer(offer.RelatedProduct.ProductId, offer.BuyerId, NewOffer.Text, offer.OfferDate,offer.Message);
                Session["offer"] = offer;
                Response.Redirect("ReviewOffer.aspx");
            }
            catch (Exception ex)
            {
                LblError1.Text = ex.Message;
                LblError1.Visible = true;
            }

        }

        protected void Cancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("ViewProduct.aspx");
        }
    }
}